package com.leijie.nio;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

/**
 * @author LeiJie
 * @time 2020-5-11 15:17
 * @desc 关于buffer的scattering 与Gathering
 * 读的时候可以传递一个buffer数组，可以用于自定义协议 区分消息header body
 */
public class NioTest10 {

    public static void main(String[] args) throws Exception{

        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        SocketAddress socketAddress = new InetSocketAddress(8899);
        serverSocketChannel.bind(socketAddress);

        int messagelen = 2+3+4;

        ByteBuffer[] buffers = new ByteBuffer[3];

        buffers[0] = ByteBuffer.allocate(2);
        buffers[1] = ByteBuffer.allocate(3);
        buffers[2] = ByteBuffer.allocate(4);

        SocketChannel socketChannel = serverSocketChannel.accept();

        while (true){
            System.out.println("开始读入数据。。，，，");
            int byteRead = 0;
            while (byteRead < messagelen){
                long r = socketChannel.read(buffers);
                byteRead += r;
                System.out.println("byteRead:"+byteRead);
                Arrays.stream(buffers).map(ByteBuffer::toString).forEach(System.out::println);
            }

            Arrays.asList(buffers).forEach(ByteBuffer::flip);

            //读满了数据 开始输出
            System.out.println("开始写数据。。。。");
            int byteWrite = 0;
            while (byteWrite < messagelen){
                long w = socketChannel.write(buffers);
                byteWrite += w;
            }

            Arrays.asList(buffers).forEach(ByteBuffer::clear);

            System.out.printf("byteRead:%d,byteWrite:%d,messageLen:%d\n",byteRead,byteWrite,messagelen);
        }


    }

}
